package com.vista.pedido;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;

import com.utilidades.CeldaRenderGeneral;

public class PanelBrowseTablaPedido extends JPanel {

	private static final Color rojo = new Color(255, 51, 0);
	private static final Color celeste = new Color(153, 204, 255);
	private static final Color naranja = new Color(255, 153, 0);

	private int coordX = 5, coordY = 5, cmbRowsPageWidth = 64, etiRowsPageWidth = 54;
	private int cmdPagWidth = 25, cmdPagHeigth = 25, marginLeft = 5, marginTop = 5;

	private int totalRows;
	private int rowsPage = 100;
	private int totalPage;
	private int visiblePages;
	private List listRows;
	private Map mapPages;
	private JButton[] cmdArrayPag;
	private JLabel etiInfo;
	private int iniItePag;
	private int iteCmd;
	private int iteIni;
	private int iteFin;
	private int idxPag;
	private int resto;
	private int numeroBoton;
	public ModeloTablaPedido modTabPed;
	public JTable tabPed;
	private CeldaRenderGeneral modTabCellRender;
	private TableColumn[] colTabPed;
	private DlgControlPedido dlgCtrlPed;
	private JScrollPane scrTabPed;
	private JComboBox cmbRowsPage;
	private List listResult;
	private JLabel etiRowsPage;

	public PanelBrowseTablaPedido(DlgControlPedido dlgCtrlPed, int left, int top, int width, int heigth) {

		this.dlgCtrlPed = dlgCtrlPed;
		super.setBorder(javax.swing.BorderFactory.createEtchedBorder());
		super.setLayout(null);
		super.setBounds(left, top, width, heigth);

		etiRowsPage = new JLabel("Reg x Pag");
		etiRowsPage.setBounds(width - (etiRowsPageWidth + marginLeft + cmbRowsPageWidth + marginLeft), coordY, 100, cmdPagHeigth);
		super.add(etiRowsPage);

		cmbRowsPage = new JComboBox();
		cmbRowsPage.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		cmbRowsPage.setFont(new Font("Tahoma", Font.PLAIN, 13));
		cmbRowsPage.addItem("100");
		cmbRowsPage.addItem("500");
		cmbRowsPage.addItem("1000");
		cmbRowsPage.addItem("5000");
		cmbRowsPage.addItem("10000");
		cmbRowsPage.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg0) {

				cmbRowsPageItemChanged(arg0);

			}
		});
		cmbRowsPage.setBounds(width - (cmbRowsPageWidth + marginLeft), coordY, cmbRowsPageWidth, cmdPagHeigth);
		super.add(cmbRowsPage);

		crearTablaPanel();

	}

	// @Override
	// public void paint(Graphics g) {
	// // super.setBorder(javax.swing.BorderFactory.createEtchedBorder());
	// // super.setLayout(null);
	// //
	// // crearTablaPanel();
	// //
	// // super.setOpaque(false);
	// // super.paint(g);
	// }// Fin de metodo de dibujad de Jpanel

	private void crearTablaPanel() {

		this.scrTabPed = new JScrollPane();
		scrTabPed.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		scrTabPed.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

		this.tabPed = new JTable();
		tabPed.setFont(new Font("Tahoma", Font.PLAIN, 14));
		tabPed.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

		this.scrTabPed.setViewportView(this.tabPed);
		super.add(this.scrTabPed);
		this.scrTabPed.setBounds(coordX, (coordY + marginTop + cmdPagHeigth), (getSize().width) - (marginLeft * 2), (getSize().height - marginTop - 35));

		/*
		 * Crear Modelo de Tabla
		 */
		this.modTabPed = new ModeloTablaPedido();
		this.tabPed.setModel(this.modTabPed);
		this.modTabCellRender = new CeldaRenderGeneral();
		try {
			this.tabPed.setDefaultRenderer(Class.forName("java.lang.String"), this.modTabCellRender);
			this.tabPed.setDefaultRenderer(Class.forName("java.lang.Integer"), this.modTabCellRender);
			this.tabPed.setDefaultRenderer(Class.forName("java.lang.Double"), this.modTabCellRender);
		} catch (ClassNotFoundException ex) {
			Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
		}

		this.tabPed.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.tabPed.getTableHeader().setReorderingAllowed(false);
		this.tabPed.setAutoResizeMode(0);
		this.tabPed.setShowGrid(true);

		String[] header = { "Documento", "Numero", "Nombre", "Modelo", "Fec-Reg", "Fec-Ent", "Temp", "Estado", "ped_cod", "cli_cod" };
		// String[] tipo = { "Date", "String", "String", "String", "String", "String", "String", "String", "Double", "String" };

		int[] ancho = { 120, 100, 200, 70, 70, 70, 30, 110, 0, 0 };

		this.colTabPed = new TableColumn[header.length];

		for (int iteHead = 0; iteHead < header.length; iteHead++) {
			this.colTabPed[iteHead] = this.tabPed.getColumn(header[iteHead]);
			this.colTabPed[iteHead].setResizable(true);
			this.colTabPed[iteHead].setPreferredWidth(ancho[iteHead]);
			// colTabPed[iteHead].addPropertyChangeListener(new ListenerCambioPropiedad());

			if (ancho[iteHead] == 0) {
				this.tabPed.getColumnModel().getColumn(iteHead).setMaxWidth(0);
				this.tabPed.getColumnModel().getColumn(iteHead).setMinWidth(0);
				this.tabPed.getTableHeader().getColumnModel().getColumn(iteHead).setMaxWidth(0);
				this.tabPed.getTableHeader().getColumnModel().getColumn(iteHead).setMinWidth(0);
			}
		}
	}

	public void crearTablaResultado(List listResult) {

		this.listResult = listResult;
		if (listResult != null) {

			totalRows = listResult.size();
			visiblePages = 5;

			totalPage = totalRows / rowsPage;
			totalPage = (totalPage < 0) ? 0 : totalPage;
			visiblePages = (visiblePages < 0) ? 0 : visiblePages;
			resto = totalRows % rowsPage;
			totalPage = (resto > 0) ? totalPage + 1 : totalPage;
			if (totalPage <= visiblePages) {
				visiblePages = totalPage;
			}

			idxPag = 0;
			iniItePag = 0;

			if (cmdArrayPag != null) {
				for (int ite = 0; ite < cmdArrayPag.length; ite++) {
					remove(cmdArrayPag[ite]);
				}
			}

			crearBotonesPaginacion("");
			llenarMapaListas(listResult);
			fillRecordTable(idxPag);
			super.repaint();

		}// Fin de if(listResult != null)
	}

	public void llenarMapaListas(List listResult) {

		if (mapPages == null) {
			mapPages = new HashMap();
		}

		mapPages.clear();

		int iteRow = 0;
		int rowsTable = 0;
		for (int itePag = 0; itePag < totalPage; itePag++) {

			listRows = new ArrayList();
			rowsTable = (listResult.size() <= rowsPage) ? listResult.size() : rowsPage;

			for (int ite = 0; ite < rowsTable; ite++) {
				if (iteRow < listResult.size()) {

					listRows.add(listResult.get(iteRow));
					iteRow++;
				}
			}
			mapPages.put(itePag, listRows);

		}
	}

	private void fillRecordTable(int idxPag) {

		setCurrentPage(idxPag);
		List listRows = (List) mapPages.get(idxPag);

		this.modTabPed.setRowCount(0);
		if (listRows != null && listRows.size() > 0) {
			this.modTabPed.setRowCount(listRows.size());
			for (int ite = 0; ite < listRows.size(); ite++) {

				String[] regTab = ((String) listRows.get(ite)).split("#");

				this.modTabPed.setValueAt(regTab[0], ite, 0);
				this.modTabPed.setValueAt(regTab[1], ite, 1);
				this.modTabPed.setValueAt(regTab[2], ite, 2);
				this.modTabPed.setValueAt(regTab[3], ite, 3);
				this.modTabPed.setValueAt(regTab[4], ite, 4);
				this.modTabPed.setValueAt(regTab[5], ite, 5);
				this.modTabPed.setValueAt(regTab[6], ite, 6);
				this.modTabPed.setValueAt(regTab[7], ite, 7);
				this.modTabPed.setValueAt(Integer.parseInt(regTab[8]), ite, 8);
				this.modTabPed.setValueAt(Integer.parseInt(regTab[9]), ite, 9);
			}
		}
	}

	public void crearBotonesPaginacion(String mover) {

		if (mover.equals("adelante")) {
			if ((idxPag + visiblePages) < totalPage) {
				this.idxPag++;
			}
		} else if (mover.equals("atras")) {
			if ((idxPag) > 0) {
				this.idxPag--;
			}
		} else {
			this.idxPag = idxPag;
		}

		numeroBoton = visiblePages;
		iniItePag = idxPag;
		iteCmd = 0;
		iteIni = 0;
		iteFin = visiblePages;
		if (totalPage > visiblePages) {
			numeroBoton = visiblePages + 2;
		}

		cmdArrayPag = new JButton[numeroBoton];

		if (totalPage > visiblePages) {

			coordX = (iteCmd * cmdPagWidth) + marginLeft;

			cmdArrayPag[0] = crearBoton(coordX, coordY, cmdPagWidth, cmdPagHeigth, -1);
			super.add(cmdArrayPag[0]);
			iteIni++;
			iteFin++;
			iteCmd++;
		}

		for (int ite = iteIni; ite < iteFin; ite++) {

			coordX = (iteCmd * cmdPagWidth) + marginLeft;
			cmdArrayPag[ite] = crearBoton(coordX, coordY, cmdPagWidth, cmdPagHeigth, iniItePag);
			super.add(cmdArrayPag[ite]);
			iteCmd++;
			iniItePag++;

		}
		if (totalPage > visiblePages) {
			coordX = (iteCmd * cmdPagWidth) + marginLeft;
			cmdArrayPag[iteCmd] = crearBoton(coordX, coordY, cmdPagWidth, cmdPagHeigth, iteCmd);
			super.add(cmdArrayPag[iteCmd]);
			iteCmd++;
		}

		if (etiInfo == null) {
			etiInfo = new JLabel();
			super.add(etiInfo);
		}
		coordX = (iteCmd * cmdPagWidth) + marginLeft;
		etiInfo.setBounds(coordX + marginLeft, coordY, 400, cmdPagHeigth);
		etiInfo.setText("Total Paginas : " + totalPage + " Total Registros : " + totalRows + " Registros por Pagina : " + rowsPage);

	}

	public JButton crearBoton(int coordX, int coordY, int cmdPagWidth, int cmdHeight, int parIndex) {

		JButton cmdPag = new JButton();
		cmdPag.setBounds(coordX, coordY, cmdPagWidth, cmdHeight);
		String nombreBoton = "";
		if (totalPage > visiblePages) {
			if (parIndex == -1) {
				nombreBoton = "atras_0";
				cmdPag.setText("<<");
			} else if (iteCmd == visiblePages + 1) {
				nombreBoton = "adelante_0";
				cmdPag.setText(">>");
			} else {
				nombreBoton = "cmdArrayPag_" + String.valueOf(parIndex);
				cmdPag.setText(String.valueOf(parIndex + 1));
			}
		} else {
			nombreBoton = "cmdArrayPag_" + String.valueOf(parIndex);
			cmdPag.setText(String.valueOf(parIndex + 1));
		}

		cmdPag.setName(nombreBoton);
		cmdPag.setActionCommand(nombreBoton);
		cmdPag.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		cmdPag.setBounds(coordX, coordY, cmdPagWidth, cmdHeight);
		cmdPag.setForeground(naranja);
		// cmdPag.setBackground(colorFondo);
		// cmdPag.setForeground(colorTexto);
		cmdPag.setMargin(new java.awt.Insets(0, 0, 0, 0));
		cmdPag.addActionListener(new cmdArrayPagListener(this));

		return cmdPag;
	}// Fin de Metodo para crear botones de dias de calendario

	public void setCurrentPage(int currentPage) {
		for (int ite = 0; ite < numeroBoton; ite++) {
			cmdArrayPag[ite].setForeground(naranja);
			String[] valCmd = cmdArrayPag[ite].getName().split("_");
			if (!valCmd[0].equals("atras") && !valCmd[0].equals("adelante")) {
				if ((Integer.parseInt(valCmd[1])) == currentPage) {
					cmdArrayPag[ite].setForeground(rojo);
				}
			}
		}
		idxPag = currentPage;
	}

	public ModeloTablaPedido getModTabPed() {
		return modTabPed;
	}

	public JTable getTabPed() {
		return tabPed;
	}

	private void cmbRowsPageItemChanged(ItemEvent arg0) {

		if (this.listResult != null) {
			rowsPage = Integer.parseInt(cmbRowsPage.getSelectedItem().toString());
			crearTablaResultado(this.listResult);
		}
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {

				DlgControlPedido frame = new DlgControlPedido(null);
				PanelBrowseTablaPedido PanelBrowseTablaPedido = new PanelBrowseTablaPedido(frame, 10, 223, 795, 391);

				frame.setLayout(null);
				frame.setSize(850, 600);
				frame.add(PanelBrowseTablaPedido);
				frame.setVisible(true);

			}
		});
	}

	/*
	 * LISTENER DE CLICK
	 */
	private static class cmdArrayPagListener implements ActionListener {

		PanelBrowseTablaPedido panelPagina;

		public cmdArrayPagListener(PanelBrowseTablaPedido panelPagina) {
			this.panelPagina = panelPagina;
		}

		@Override
		public void actionPerformed(ActionEvent e) {

			JButton objCmd = (JButton) e.getSource();
			String[] valCmd = objCmd.getActionCommand().split("_");
			if (valCmd[0].equals("atras") || valCmd[0].equals("adelante")) {

				if (panelPagina.cmdArrayPag != null) {
					for (int ite = 0; ite < panelPagina.cmdArrayPag.length; ite++) {
						panelPagina.remove(panelPagina.cmdArrayPag[ite]);
					}
					panelPagina.repaint();
					panelPagina.crearBotonesPaginacion(valCmd[0]);

				}

			} else {
				int idxPag = Integer.parseInt(valCmd[1]);
				panelPagina.fillRecordTable(idxPag);
			}
			// System.out.println("bootn : " + objCmd.getActionCommand());
		}// Fin de Action performed del boton de la palanca
	}// fin de la clase estatica para escuchar las acciones de los botones de palanca
}
